/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2025-06-19
 * Time: 23:57
 */
//力扣：https://leetcode.cn/problems/reverse-linked-list/submissions/637899577/
//给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    public static void printNode(ListNode list){
        System.out.print("[");
        while(list!=null){
            System.out.print(" "+list.val);
            list=list.next;
        }
        System.out.print(" ]");
        System.out.println("");
    }
 }
public class Test {
    public static ListNode reverseList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode p1=head;
        ListNode p2=head.next;
        ListNode p3=head.next.next;
        head.next=null;
        while(p3!=null){
            p2.next=p1;
            p1=p2;
            p2=p3;
            p3=p3.next;
        }
        p2.next=p1;
        return p2;
    }

    public static void main(String[] args) {
        ListNode list5 = new ListNode(5,null);
        ListNode list4 = new ListNode(4,list5);
        ListNode list3 = new ListNode(3,list4);
        ListNode list2 = new ListNode(2,list3);
        ListNode list1 = new ListNode(1,list2);
        ListNode head=list1;
        ListNode.printNode(head);
        head=reverseList(list1);
        ListNode.printNode(head);
    }
}
